package cn.edu.nchu.comic_strip.ui.collection;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

import cn.edu.nchu.comic_strip.App;
import cn.edu.nchu.comic_strip.R;
import cn.edu.nchu.comic_strip.database.dao.BookDao;
import cn.edu.nchu.comic_strip.database.dao.PageDao;
import cn.edu.nchu.comic_strip.entity.Book;
import cn.edu.nchu.comic_strip.entity.Page;

public class CollectionBookDetailActivity extends AppCompatActivity {
    private PageDao pageDao = App.getAppDatabase().getPageDao();
    private BookDao bookDao = App.getAppDatabase().getBookDao();

    private CollectionBookDetailAdapter adapter;
    private ListView listView;
    private ImageView bookCoverImageView;
    private TextView bookNameTextView;
    private TextView collectionCountTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.collection_book_detail_list);

        // Hide the ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        int bookId = getIntent().getIntExtra("bookId", -1);
        List<Page> bookmarkedPages = pageDao.getCollectionByBookId(bookId);
        Book book = bookDao.getBook(bookId);

        bookCoverImageView = findViewById(R.id.book_cover);
        bookNameTextView = findViewById(R.id.book_name);
        collectionCountTextView = findViewById(R.id.collection_count);

        if (book != null) {
            bookCoverImageView.setImageResource(getResources().getIdentifier(book.getBookCover(), "drawable", getPackageName()));
            bookNameTextView.setText(book.getBookName());
            int collectionCount = bookmarkedPages.size();
            collectionCountTextView.setText(String.valueOf(collectionCount) + "个收藏");
        }

        listView = findViewById(R.id.collection_book_detail_list);

        adapter = new CollectionBookDetailAdapter(this, bookmarkedPages);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent("cn.edu.nchu.comic_strip.ui.bookpage.BookPageActivity");
            intent.putExtra("stopPage", bookmarkedPages.get(position).getPageNum()-1); // 传输书签的页数
            intent.putExtra("bookId", bookId); // 传输书的id
            startActivity(intent);  // 启动 ComicActivity
        }); // 收藏

        listView.setAdapter(adapter);
    }
}
